import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:myapp/api/Http.dart';
import 'package:myapp/api/Urls.dart';
import 'package:myapp/model/UnitUrlModel.dart';
import 'package:myapp/page/HelpPage.dart';
import 'package:myapp/r.dart';
import 'package:myapp/util/Constant.dart';
import 'package:myapp/util/MyNavigator.dart';
import 'package:url_launcher/url_launcher.dart';

class SearchCouponPage extends StatefulWidget {
  @override
  _SearchCouponPageState createState() => _SearchCouponPageState();
}

class _SearchCouponPageState extends State<SearchCouponPage>
    with SingleTickerProviderStateMixin {
  TextEditingController _textEditingController;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _textEditingController = TextEditingController();
    _textEditingController.addListener(() {
      ///获取输入的内容
      inputStr = _textEditingController.text;
    });
    getClipbordData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("复制商品链接"),
        actions: <Widget>[
          GestureDetector(
            onTap: () {
              //跳往教程
              MyNavigator.push(context, HelpPage());
            },
            child: Row(
              children: <Widget>[
                IconButton(
                  icon: Icon(
                    Icons.help,
                    color: Colors.white,
                  ),
                ),
                Text("复制链接教程")
              ],
            ),
          )
        ],
      ),
      body: Container(
        padding: const EdgeInsets.all(12),
        child: Column(
          children: <Widget>[
            _buildUrlInput(context),
            MaterialButton(
              minWidth: double.infinity,
              child: Text(
                "生成有券链接",
                style: TextStyle(color: Colors.white),
              ),
              color: Colors.blueAccent,
              onPressed: () {
                getPushUrl();
              },
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _textEditingController.dispose();
  }

  String inputStr = "";

  void getPushUrl() {
    if (inputStr.isNotEmpty) {
      Map<String, dynamic> map = {"source_url": inputStr, "pid": Constant.pId};
      DioUtils.postHttp(Urls.UnitUrl, parameters: map, onSuccess: (data) {
        UnitUrlModel unitUrlModel = UnitUrlModel.fromMap(jsonDecode(data));
        _launchURL(unitUrlModel.goodsZsUnitGenerateResponse.url);
      }, onError: (err) {});
    }
  }

  void _launchURL(String url) async {
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      print('不能访问');
    }
  }

  //显示剪切板dialog
  void getClipbordData() async {
    var data = await Clipboard.getData(Clipboard.kTextPlain);
    if (data.text.isNotEmpty) {
      showDialog(
          context: context,
          barrierDismissible: false,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text("粘贴板"),
              content: Text(data.text),
              actions: <Widget>[
                FlatButton(
                  child: Text("关闭"),
                  onPressed: () {
                    Navigator.pop(context);
                  },
                ),
                FlatButton(
                  child: Text("确定"),
                  onPressed: () {
                    _textEditingController.text = data.text;
                    Navigator.pop(context);
                    setState(() {});
                  },
                ),
              ],
            );
          });
    }
  }

  Widget _buildUrlInput(BuildContext context) {
    return Card(
      child: Container(
        padding: const EdgeInsets.all(8),
        child: TextField(
          controller: _textEditingController,
          showCursor: true,
          cursorColor: Colors.grey,
          // 光标颜色
          maxLines: 8,
          decoration: InputDecoration(
            hintText: "粘贴商品链接",
            border: InputBorder.none,
          ),
          onChanged: (data) {
            inputStr = data;
          },
        ),
      ),
    );
  }
}
